package com.sunther.document.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author csb
 * @description: TODO
 * @date 2023/5/9 10:50
 */
@Component
public class JwtUtils {

    @Value("${token.key}")
    String key;

    public String createJWT(Long userId, String name, String nickName, String projectId, Integer roleId, String roleName) {
        //生成JWT
        String token = JWT.create()
                .setPayload("userId", userId)
                .setPayload("name", name)
                .setPayload("nickName", nickName)
                .setPayload("projectId", projectId)
                .setPayload("roleId", roleId)
                .setPayload("roleName", roleName)
                .setKey(key.getBytes(StandardCharsets.UTF_8))
                .setIssuedAt(DateTime.now())
                .setExpiresAt(DateUtil.offsetDay(DateTime.now(),1))
                .sign();
        return token;
    }
    public String createJWT(String id, String sub, Map<String, Object> map){
        //生成JWT
        String token = JWT.create()
                .setPayload("id", id)
                .setPayload("sub", sub)
                .setPayload("map", map)
                .setKey(key.getBytes(StandardCharsets.UTF_8))
                .setIssuedAt(DateTime.now())
                .setExpiresAt(DateUtil.offsetDay(DateTime.now(),1))
                .sign();
        return token;
    }

    public Boolean parseJWT(String token){
        //验证时间
        try {
            JWTValidator.of(token).validateDate(DateUtil.date());
        }catch (Exception e) {
            return false;
        }

        return JWT.of(token).setKey(key.getBytes(StandardCharsets.UTF_8)).verify();
    }


}
